//
//  TLMessageCenterViewController.m
//  WXReader
//
//  Created by huaya on 2025/3/19.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLMessageCenterViewController.h"
#import "HMSegmentedControl.h"
#import "TLMessageViewController.h"
#import "TLMsgNotificationViewController.h"
#import "TLUnReadModel.h"

@interface TLMessageCenterViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIView *navView;
@property (nonatomic, strong) UILabel *navTitleLab;
@property (nonatomic, strong) HMSegmentedControl *segControl;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSMutableArray<UIViewController *> *viewControllers;

// 新增属性
@property (nonatomic, assign) CGFloat lastContentOffsetX;

@property (nonatomic, strong) UILabel *leftRedLab;
@property (nonatomic, strong) UILabel *rightRedLab;

@property (nonatomic, strong) TLUnReadModel *unReadModel;

@property (nonatomic, strong) TLMsgNotificationViewController *vc2;

@end

@implementation TLMessageCenterViewController
// TLMessageCenterViewController.m
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 保存当前滚动位置
    self.lastContentOffsetX = self.scrollView.contentOffset.x;
}
// TLMessageCenterViewController.m
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 恢复滚动位置
    [self.scrollView setContentOffset:CGPointMake(self.lastContentOffsetX, 0) animated:NO];
    // 同步分段控件选中状态
    NSInteger currentIndex = self.lastContentOffsetX / self.view.bounds.size.width;
    [self.segControl setSelectedSegmentIndex:currentIndex animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self setUI];
    [self netWork];
}
- (void)setUI{
    [self.view addSubview:self.navView];
    [self.view addSubview:self.segControl];
    
    MK_WEAK_SELF
    self.segControl.indexChangeBlock = ^(NSInteger index) {
        NSInteger selectedIndex = index;
        [weakSelf setActiveViewControllerAtIndex:selectedIndex];
        [weakSelf netWork];
    };
    
    // 配置 UIScrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.bounces = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.segControl.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [self.scrollView layoutIfNeeded];
    
    TLMessageViewController *vc = [[TLMessageViewController alloc] init];
    [vc resetFrame: CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, self.scrollView.frame.size.height)];
    [self addChildViewController:vc];
    [self.viewControllers addObject:vc];
    [self.scrollView addSubview:vc.view];
    
    TLMsgNotificationViewController *vc2 = [[TLMsgNotificationViewController alloc] init];
    [vc2 resetFrame: CGRectMake(0, 0, SCREEN_WIDTH, self.scrollView.frame.size.height)];
    [self addChildViewController:vc2];
    [self.viewControllers addObject:vc2];
    self.vc2 = vc2;
    [self.scrollView addSubview:vc2.view];
    
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, self.scrollView.frame.size.height);
    
    [self.view addSubview:self.leftRedLab];
    [self.view addSubview:self.rightRedLab];
}
- (UILabel *)leftRedLab{
    if (!_leftRedLab) {
        _leftRedLab = [[UILabel alloc] init];
        _leftRedLab.backgroundColor = [UIColor redColor];
        _leftRedLab.layer.masksToBounds = YES;
        _leftRedLab.layer.cornerRadius = 15/2;
        _leftRedLab.textColor = [UIColor whiteColor];
        _leftRedLab.font = SYSTEM_FONT(10);
        _leftRedLab.text = @"99";
        _leftRedLab.textAlignment = NSTextAlignmentCenter;
        _leftRedLab.hidden = YES;
        
        CGFloat baseScreenWidth = 390.0;
        CGFloat originalLeft = 150.0;
        CGFloat screenWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
        // 3. 计算动态调整后的 left 值
        CGFloat scaleFactor = screenWidth / baseScreenWidth;
        
        CGFloat adjustedLeft = originalLeft * scaleFactor;
        
        _leftRedLab.frame = CGRectMake(adjustedLeft, PUB_NAVBAR_HEIGHT, 26, 15);
    }
    return _leftRedLab;
}
- (UILabel *)rightRedLab{
    if (!_rightRedLab) {
        _rightRedLab = [[UILabel alloc] init];
        _rightRedLab.backgroundColor = [UIColor redColor];
        _rightRedLab.layer.masksToBounds = YES;
        _rightRedLab.layer.cornerRadius = 15/2;
        _rightRedLab.textColor = [UIColor whiteColor];
        _rightRedLab.font = SYSTEM_FONT(10);
        _rightRedLab.text = @"99";
        _rightRedLab.textAlignment = NSTextAlignmentCenter;
        _rightRedLab.hidden = YES;
        
        CGFloat baseScreenWidth = 390.0;
        CGFloat originalLeft = 310;
        CGFloat screenWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
        // 3. 计算动态调整后的 left 值
        CGFloat scaleFactor = screenWidth / baseScreenWidth;
        
        CGFloat adjustedLeft = originalLeft * scaleFactor;
        
        _rightRedLab.frame = CGRectMake(adjustedLeft, PUB_NAVBAR_HEIGHT, 26, 15);
    }
    return _rightRedLab;
}
- (NSMutableArray<UIViewController *> *)viewControllers{
    if (!_viewControllers) {
        _viewControllers = [[NSMutableArray alloc] init];
    }
    return _viewControllers;
}
- (UIView *)navView{
    if (!_navView) {
        _navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, PUB_NAVBAR_HEIGHT)];
        [_navView setBackgroundColor:[UIColor whiteColor]];
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(6, PUB_NAVBAR_HEIGHT - 28 - 6, 28, 28)];
        [_backBtn setImage:[UIImage imageNamed:@"tzxqy_fh"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navView addSubview:_backBtn];
        
        _navTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, PUB_NAVBAR_HEIGHT - 28 - 6, kScreenWidth, 28)];
        _navTitleLab.text = @"Inbox";
        _navTitleLab.textColor = [UIColor colorWithHexString:@"#000000"];
        _navTitleLab.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
        _navTitleLab.textAlignment = NSTextAlignmentCenter;
        [_navView addSubview:_navTitleLab];
        _navView.backgroundColor = [UIColor whiteColor];
        _navTitleLab.textColor = [UIColor blackColor];
    }
    return _navView;
}
- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (HMSegmentedControl *)segControl{
    if (!_segControl) {
        _segControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"Messages",@"Notifications"]];
        _segControl.backgroundColor = UIColor.clearColor;
        _segControl.titleTextAttributes = @{NSFontAttributeName : BOLD_SYSTEM_FONT(16),
                                            NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#000000"]};
        _segControl.selectedTitleTextAttributes = @{NSFontAttributeName :BOLD_SYSTEM_FONT(16),
                                                    NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#9E6DFC"]};
        _segControl.selectionIndicatorHeight = 2.0f;
        _segControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        _segControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segControl.selectionIndicatorColor = [UIColor colorWithHexString:@"#9E6DFC"];
        
        _segControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed;
        
        _segControl.frame = CGRectMake(40, PUB_NAVBAR_HEIGHT, kScreenWidth-80, 40);
    }
    return _segControl;
}

#pragma mark - event
- (void)setActiveViewControllerAtIndex:(NSInteger)index {
    // 更新 scrollView 的内容偏移量
    [self.scrollView setContentOffset:CGPointMake(self.view.bounds.size.width * index, 0) animated:YES];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 当滚动停止时更新 segment 控件
    NSInteger pageIndex = scrollView.contentOffset.x / self.view.bounds.size.width;
    self.segControl.selectedSegmentIndex = pageIndex;
}
- (void)netWork{
    MJWeakSelf
    [APIManager sendPostRequest:[APIURLManager notUnReadCount] parameters:@{} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            self.unReadModel = [TLUnReadModel mj_objectWithKeyValues:requestModel.data];
            
            self.leftRedLab.hidden = self.rightRedLab.hidden = YES;
            
            if (self.unReadModel.sysMessages.intValue != 0) {
                
                self.rightRedLab.hidden = NO;
                self.rightRedLab.text = self.unReadModel.sysMessages.stringValue;
            }
            
            if (self.unReadModel.replyMessages.intValue+self.unReadModel.likeMessages.intValue > 0) {
                
                self.leftRedLab.hidden = NO;
                self.leftRedLab.text = [NSString stringWithFormat:@"%d",self.unReadModel.replyMessages.intValue+self.unReadModel.likeMessages.intValue];
                
            }
            
            weakSelf.vc2.unReadModel = self.unReadModel;
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

@end
